<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Parent Page</title>
    <style>
      .box {
        background: #eee;
        padding: 10px;
        margin: 20px;
      }
    </style>
  </head>
  <body>
    <div class="box">
      <h3>window.open(url, target)</h3>
      <h4>如果要打开新窗口，而不是新tab，则需要指定windowFeature参数！！</h4>
    </div>

    <div class="box">
      <h4>storage event note:</h4>
      <p>
        parent window listen storage event, update some localStorage in other
        same domain page
      </p>
    </div>

    <div class="box">
      <button onclick="testOpen()">
        open child-window and child-window listen message
      </button>
      <div id="childListenResult">
        <p>
          childWin.addEventListener is available, but not effect, can not
          recieve message
        </p>
        <p>can not recieve message by this way</p>
      </div>
    </div>

    <div class="box">
      <button onclick="testClose()">close window</button>
      <p>childWin.close() success</p>
    </div>

    <div class="box">
      <button onclick="sendChild()">
        parent-win post message to child-win
      </button>
      <p>
        childWin.opener.addEventListener is not available, will throw cors error
      </p>
    </div>

    <div class="box">
      <button onclick="sendChild2()">child-win post message</button>
      <h4>父: ChildWin.postMessage, window.listen P -> C</h4>
      <p>standard way to communicate with child</p>
      <p>in the new subwindow, it can recieve the message</p>
    </div>

    <div class="box">
        <button onclick="sendChild2({name: 'lufy', age: 12})">child-win post message object</button>
        <p>childWin.postMessage({name: 'lufy', age: 12}, '*'),  object instead of string, success</p>
        <p>postMessage 会自动把对象序列化为字符串</p>
        <p>message 事件回调会自动把 event.data 反序列化为对象</p>
    </div>

    <div class="box">
      <h4>父: window.listen, parentWin.postMessage C -> P</h4>
      <p>standard way to communicate with parent</p>
      <div id="parentMsgResult"></div>
    </div>

    <div class="box">
      <h3>
        实际上父子窗口都拥有对方的window对象，用这个对象的 postMessage
        可以发消息出去 :)
      </h3>
    </div>

    <script>
      function outputMsg(msg, id = "output") {
        const p = document.createElement("p");
        p.innerText = msg;
        document.getElementById(id).appendChild(p);
      }

      let childWin = "";
      function testOpen() {
        // const windowFeatures = 'width=800,height=600,resizable,scrollbars';
        const windowFeatures = "";

        // childWin = window.open("https://www.mozilla.org/", "newwindow", windowFeatures);
        childWin = window.open(
          "http://localhost:8081/child.html" + `?ts=${Date.now()}`,
          "newWindow",
          windowFeatures
        );

        // console.log("🚀 ~ testOpen ~ childWin:", childWin)

        // console.log(childWin.favcolor,'<---------favcolor') // cross-origin disable to access childWin property
        console.log(
          "🚀 ~ childWin.addEventListener ~ childWin.addEventListener:",
          childWin.addEventListener
        );

        childWin.addEventListener("storage", function (event) {
          console.log("=========== storage event", event);
        });

        // cross-origin error
        childWin.addEventListener("message", function (event) {
          console.log("CHILD-WIN LISTEN message callback: ", event.data);
        });

        console.log("----------> childWin listen message done.");

        window.external.comeback = function () {
          var back = confirm("Are you sure you want to comback?");
          if (back) {
            childWin.close();
          } else {
            childWin.focus();
          }
        };
      }

      window.addEventListener("message", function (event) {
        // ok
        console.log("PARENT-WIN LISTEN message callback: ", event.data);
        outputMsg(event.data, "parentMsgResult");
      });

      console.log(
        "parent window listen storage event, update some localStorage in other same domain page"
      );
      window.addEventListener("storage", function (event) {
        // ok
        console.log("PARENT-WIN LISTEN storage callback: ", event);
      });

      function testClose() {
        childWin.close();
      }

      function sendChild() {
        window.postMessage("PARENT-WIN SAY: Hello from parent!", "*");
      }

      function sendChild2(msg = 'CHILD-WIN SAY: Hello from parent 2!') {
        childWin.postMessage(msg, "*");
      }
    </script>
  </body>
</html>
